/*
* @Date: 2021/2/1
* @Author: XueChengwu <xuechengwu@erayt.com>
* @Copyright: 2015-2019 Erayt, Inc.
* @Description: If you have some questions, please contact: xuechengwu@erayt.com.
*/
import React from 'react';
import '../../scss/app.scss';
import Fragment from '../../components/Fragment';
import RemoteTable from '../../components/RemoteTable';
import { Table, Icon, Switch, Button, message } from 'antd';
import connect from 'react-redux/es/connect/connect';
import ReactDOM from 'react-dom';
import {authAction} from '../../actions/auth'
import configStore from '../../store'
import {loginReducer} from '../../reducers/login';
import Provider from "react-redux/es/components/Provider";
import { get, post } from '../../utils/http';
import Validator from '../../validator';
import Form from './form';
import SymbolValidator from '../../validator/symbol';
import ws from '../../ws';

@Fragment('symbol?type=forex')
class App extends React.Component {
  componentDidMount () {
    ws.subscribe([{
      title: 'MARKVO',
      callback: (res) => {
        console.log(res);
      }
    }], 'forex');
  }

  onChecked = async (checked, record) => {
    try{
      let data = await post('/symbol/status', { id: record.id, status: checked ? 1 : 2 })
      message.info(data.msg);
      this.refs.symbolTable.refresh();
    }catch(err) {
      if(err.type === 1) {
        message.error(err.error)
      }
      console.error(err)
    }
  }

  onEdit = (record) => {
    const form = { ...record };
    this.context.modal(
      <Form
        record={form}
      />,
      '编辑合约',
      async () => {
        let validator = new Validator(SymbolValidator)
        let res = await validator.check(form)
        if(res !== true) {
          message.error(res)
          return false
        }
        try{
          let data = await post('/symbol/edit', { ...form  })
          message.info(data.msg)
          this.refs.symbolTable.refresh()
          return true
        }catch(err){
          if(Number(err.type) === 1) {
            message.error(err.error)
            return false
          }
        }
      }
    );
  }

  onDelete = async (record) => {
    try{
      let data = await post('/symbol/del', { id: record.id });
      message.info(data.msg);
      this.refs.symbolTable.refresh();
    }catch(err) {
      if(err.type === 1) {
        message.error(err.error);
      }
    }
  }

  onAdd = async () => {
    const form = {};
    this.context.modal(
      <Form record={form} />,
      '添加合约',
      async () => {
        let validator = new Validator(SymbolValidator)
        let res = await validator.check(form)
        if(res !== true) {
          message.error(res)
          return false
        }
        try{
          let data = await post('/symbol/add', { ...form })
          message.info(data.msg)
          this.refs.symbolTable.refresh()
          return true
        }catch(err){
          if(Number(err.type) === 1) {
            message.error(err.error)
            return false
          }
        }
      }
    );
  }

  onMarkvo = async () => {
    try {
      let data = await post('/symbol/doMarkvo', {});
      message.info(data.msg);
    } catch(err) {
      if (Number(err.type) === 1) {
        message.error(err.error);
      }
    }
  }

  onCalcBayes = async (record) => {
    try {
      let data = await post('/symbol/calcBayes', { symbol: record.secid });
      message.info(data.msg);
    } catch(err) {
      if (Number(err.type) === 1) {
        message.error(err.error);
      }
    }
  }

  render() {
    return (
      <div className="full-screen">
        <div className="app-operation">
          <Button onClick={this.onAdd}>新增</Button>
          <Button onClick={this.onMarkvo}>Markvo计算</Button>
        </div>
        <RemoteTable
          url="/symbol/list"
          ref="symbolTable"
          dataProxy={(result) => {
            if (Number(result.code) === 0 && result.data && result.data.records) {
              const { data = [], cur, pageSize, total } = result.data.records;
              return {
                data,
                pagination: {
                  current: cur,
                  pageSize,
                  total,
                }
              }
            }
            return {
              data: [],
              pagination: {}
            };
          }}
        >
          <Table.Column
            title="合约名称"
            dataIndex="name"
            key="name"
          />
          <Table.Column
            title="合约代码"
            dataIndex="symbol"
            key="symbol"
          />
          <Table.Column
            title="产品代码"
            dataIndex="secid"
            key="secid"
          />
          <Table.Column
            title="行情图表"
            dataIndex="lineType"
            key="lineType"
          />
          <Table.Column
            title="文根"
            dataIndex="prefix"
            key="prefix"
          />
          <Table.Column
            title="URL"
            dataIndex="url"
            key="url"
          />
          <Table.Column
            title="状态"
            dataIndex="status"
            key="status"
            render={(text, record) => (
              <Switch
                checkedChildren="启用"
                unCheckedChildren="禁用"
                checked={Number(record.status) === 1}
                onChange={(checked) => this.onChecked(checked, record)}
              />
            )}
          />
          <Table.Column
            title="有效位数"
            dataIndex="decimal"
            key="decimal"
          />
          <Table.Column
            title="操作"
            dataIndex="action"
            key="action"
            render={(text, record) => (
              <span>
                <Icon type="edit" onClick={() => {this.onCalcBayes(record)}} />
                <Icon type="edit" onClick={() => {this.onEdit(record)}} />
                <Icon type="close" onClick={() => {this.onDelete(record)}} />
            </span>
            )}
          />
        </RemoteTable>
      </div>
    );
  }
}

const Page = connect(
  state => ({isloading:state.isloading,errMsg: state.errMsg}),
  { authAction }
)(App)

let store = configStore(loginReducer)
ReactDOM.render(
  <Provider store={store}><Page/></Provider>,
  document.getElementById('root')
)
